var MsgUser = sessionStorage.getItem("user");
//转成js
var uid = JSON.parse(MsgUser).id;

$(function (){
    //初始化数据
    InitUserAddress();
    //删除收货地址
    deleteById();
    //添加收货地址
    $("#tj-btn").click(function () {
       let  formData= $("#form-add-address").serialize();
        $.post(
            "AddressSava",
            formData+"&userid="+uid,
            function (msg) {
                if (msg.data == 1) {
                    alert("添加成功");
                    //刷新页面
                    location.reload();
                    //清空表单数据
                    $("#form-add-address")[0].reset();
                } else {
                    alert("添加失败");
                }
            },
            "json"
        )
    })
});

//查询当前用户全部的收获地址
function InitUserAddress(){
    $.get(
        "AddressQueryByUserid",
        {userid:uid},
        function (msg){
           let addre=msg.data;
            for (let i = 0; i < addre.length; i++) {
                let tr=$(`<tr>
                                <td>${addre[i].contacts}</td>
                                <td>${addre[i].tel}</td>
                                <td>${addre[i].address}</td>
                                <td>
                                    <button  class="btn btn-sm py-0 btn-outline-danger deleteById" type="button" data-id="${addre[i].id}">
                                        <i class="glyphicon-remove"></i>
                                        <span class="hidden-xs">移除</span>
                                    </button>
                                </td>
                          </tr>`);
                //把数据追加进去
                $("#tbody").append(tr);
            }
        },
        "json"
    )
}
//删除收货地址
function deleteById(){
    $("#tbody").on("click","tr > td > .deleteById",function (){
        let id = $(this).data("id");
        if (confirm("确定要删除吗")){
            $.get(
                "AddressDeleteById",
                {id:id},
                function (msg){
                    if (msg.data==1){
                        //成功刷新页面
                        location.reload();
                    }else {
                        alert("数据有误，请重新尝试");
                    }
                },
                "json"
            )
        }
    });
}


